//
//  BuyAiCountViewModel2.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/3.
//

import Foundation
import LeanCloud
//无限畅聊
class BuyAiCountViewModel2 : AiActViewModel {
    @Published var items = [AiCountConfigActBean]()
    @Published var selectedIndex: Int = 0
    @Published var status = ""
    @Published var loadDialog = true
    
    func getData(_ isRefresh: Bool = false) {
        requestList(isRefresh: isRefresh) {
            let query = LCQuery(className: "AiCountConfigAct")
            query.whereKey("hide", .equalTo(false))
            query.whereKey("sort", .ascending) //升序
            let list =  try await LeancloudManager.instance.getList(query: query, modeType: AiCountConfigActBean.self)
            try check(!isRefresh || !list.isEmpty, "暂无数据")
            return list
        } suc: { diarys in
            self.status = ""
            self.items.append(contentsOf: diarys)
        } fail: {
            self.status = $0.message
        }
    }
    
    func getProductId() -> String {
        return items[selectedIndex].productId ?? ""
    }
    
    func getBean() -> AiCountConfigActBean {
        return items[selectedIndex]
    }
    
    func doBuy(productID: String, bean: AiCountConfigActBean) {
        request {
            //预先购买记录
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                var record = VipPrePayRecordBean()
                record.userId = userManager.getUserId()
                record.userName = userManager.getName()
                record.channel = "apple"
                record.payType = bean.title
                record.json = toJson(bean)
                try await LeancloudManager.instance.save(todo: record)
            }
            if let user = userManager.getUser() {
                try await retry(maxRetries: 5, retryDelayMillis: 200) {
                    let day : Int = bean.day ?? 0
                    let addTime = (1000 * 60 * 60 * 24 * day)
                    user.aiChatCountExpiration = getMillisecond(getNetTimeLocal()) + Int64(addTime)
                    try await LeancloudManager.instance.save(todo: user)
                    userManager.saveUser(user)
                }
            }
            try await retry(maxRetries: 5, retryDelayMillis: 200) {
                try await InviteRewardUtils.doBuyCount(userManager.getUser()?.inviteUserId, bean.title ?? "",bean.inviteCount ?? 0)
            }
            //更新数量
            try await LeancloudManager.instance.incrementKey(className: AiCountConfigActBean().getCloudTable(), objectId: bean.objectId ?? "", key: "count", value: -1)

            //更新明天key不处理，安卓处理就行
           
            return true
        } suc: { _ in
            showToast("购买成功")
            hideLoadPopup()
        } fail: {_ in
            hideLoadPopup()
        }
    }
    
}
